<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/18
 * Time: 16:10
 */

namespace App\Client;


use Psr\Log\LoggerInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class WebhookApp
{

    /**
     * Annotation combined with phpdoc:
     *
     * @Inject("settings")
     */
    public $settings;

    /**
     * Annotation combined with phpdoc:
     *
     * @Inject
     * @var LoggerInterface
     */
    public $logger;

    public function webhook(Request $request, Response $response, $args): Response
    {
        $secret = 'test@123456';
        $root_dir = $this->settings['root_dir'];
        $signature = $_SERVER['HTTP_X_GITEE_TOKEN'] ?? '';
        $event = $_SERVER['HTTP_X_GITEE_TOKEN'] ?? '';
        $delivery = $_SERVER['HTTP_X_GITEE_TIMESTAMP'] ?? '';
        $payload = file_get_contents('php://input');

        if (!isset($signature, $event, $delivery)) return $this->response($response, 'error');
        if (!($signature === $secret)) return $this->response($response, 'error');

        $data = json_decode($payload, true);
        $repository = $data['repository']['name'] ?? '';
        if (empty($repository)) return $this->response($response, 'error');

        $deploy_dir = $root_dir . '/gitbooks/' . $repository;
        if (file_exists($deploy_dir)) {
            $deploy = $deploy_dir . '/deploy.lock';
            file_put_contents($deploy, 1);
            return $this->response($response, 'ok');
        } else {
            $deploy_dir = $root_dir . '/gitbooks/ones/' . $repository;
            if (file_exists($deploy_dir)) {
                $deploy = $deploy_dir . '/deploy.lock';
                file_put_contents($deploy, 1);
                return $this->response($response, 'ok');
            }
            return $this->response($response, 'error');
        }
    }

    private function response(Response $response, $html)
    {
        $body = $response->getBody();
        $body->write($html);
        return $response;
    }
}